<?php

namespace app\home\controller;

use app\common\controller\Home;

class Business extends Home
{
    protected $EmsModel;
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->EmsModel = model('Ems');
    }
    // 我的页面
    public function index()
    {
        $this->assign([
            'active3' => 'mui-active'
        ]);
        return $this->fetch();
    }
    // 修改个人信息
    public function profile()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $LoginUser = $this->LoginUser;
            $data = [];
            $nickname = $params['nickname'] ?? '';
            $email = $params['email'] ?? '';
            $password = $params['password'] ?? '';
            $gender = $params['gender'] ?? 0;
            $code = $params['code'];
            if ($_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                $res = upload('avatar');
                if ($res['code'] == 0) {
                    $this->error($res['msg']);
                }

                $data['avatar'] = $res['data'];
            }
            if ($code != null) {
                $parentpath = $this->RegionModel->where('code', $code)->value('parentpath');
                if ($parentpath) {
                    $addcode = explode(',', $parentpath);
                    $data['province'] = $addcode[0] ?? '';
                    $data['city'] = $addcode[1] ?? '';
                    $data['district'] = $addcode[2] ?? '';
                } else {
                    $this->error("修改失败,无该地区信息");
                }
            }

            if ($nickname != null && $nickname != $LoginUser['nickname']) {
                $data['nickname'] = $nickname;
            }
            if ($email != null && $email != $LoginUser['email']) {
                 $this->EmsModel->destroy(['email' => $LoginUser['email']]);
                $data['email'] = $email;
            }
            if ($gender != $LoginUser['gender']) {
                $data['gender'] = $gender;
            }
            if ($password != null) {
                $salt = randstr();
                $password = md5($password . $salt);
                $data['password'] = $password;
                $data['salt'] = $salt;
            }
            if (count($data) > 0) {
                $data['id'] = $LoginUser['id'];
            } else {
                $this->success('修改成功', 'home/business/index');
            }
            $ret = $this->BusinessModel->isUpdate(true)->save($data);
            if ($ret) {
                if ($_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                    if ($LoginUser['avatar']) {
                        // 删除旧的图片
                        $path = ltrim($LoginUser['avatar'], '/');
                        is_file($path) && unlink($path);
                    }
                }

                $this->success('修改成功', 'home/business/index');
            } else {
                if ($_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                    $path = ltrim($data['avatar'], '/');
                    is_file($path) && unlink($path);
                }
                $this->error("修改失败");
            }
        }
        return $this->fetch();
    }
    // 联系我们页面
    public function contact()
    {
        $contacts = config('site.contacts');
        $telephone = config('site.telephone');
        $address = config('site.address');
        $subjectlist = $this->SubjectModel->field('id,title,thumbs')->order('createtime', 'desc')->limit(5)->select();
        $this->assign([
            'contacts' => $contacts,
            'telephone' => $telephone,
            'address' => $address,
            'subjectlist' => $subjectlist
        ]);
        return $this->fetch();
    }
    // 邮箱页面
    public function email()
    {
        if ($this->request->isPost()) {
            $code = $this->request->param('code', '', 'trim');
            $emailinfo = $this->EmsModel->where('email', $this->LoginUser['email'])->find();
            $expired = strtotime($emailinfo['createtime']) + 60;
            if ($expired < time()) {
                $EmailStatus = $this->EmsModel->destroy($emailinfo['id']);
                $this->error('验证码已经过期，请重新发起邮箱验证');
            }
            if ($code == $emailinfo['code']) {
                // 开启事务
                $this->EmsModel->startTrans();
                $this->BusinessModel->startTrans();
                $BusinessStatus = $this->BusinessModel->where('id', $this->LoginUser['id'])->update(['auth' => '1']);
                if ($BusinessStatus === false) {
                    $this->error($this->BusinessModel->getError());
                }
                $EmailStatus = $this->EmsModel->destroy($emailinfo['id']);

                if ($EmailStatus === false) {
                    $this->BusinessModel->rollback();
                    $this->error($this->EmsModel->getError());
                }
                $this->BusinessModel->commit();
                $this->EmsModel->commit();
                $this->success('邮箱认证成功', 'home/business/index');
            } else {
                $this->error('验证码错误');
            }
        }
        return $this->fetch();
    }
    // 发生邮箱
    public function send()
    {
        if ($this->request->isPost()) {

            $emailinfo = $this->EmsModel->where('email', $this->LoginUser['email'])->find();

            if ($emailinfo) {
                $this->error('已发送验证码，请去邮箱查收');
            }
            // 开启事务
            $this->EmsModel->startTrans();

            // 验证码
            $code = randstr(4);

            $data = [
                'event' => '邮箱认证',
                'email' => $this->LoginUser['email'],
                'code' => $code,
            ];
            $restult = $this->EmsModel->validate('common/Ems')->save($data);
            if (!$restult) {
                $this->error('验证码发送失败');
            }
            $email = new \app\common\library\Email;
            $res = $email->subject('云课堂邮箱验证码')->to($this->LoginUser['email'])->message('云课堂验证码：' . $code)->send();
            if (!$res) {
                $this->EmsModel->rollback();
                $this->error('验证码发送失败');
            }
            $this->EmsModel->commit();
            $this->success('验证码发送成功');
        }
    }
    // 我的消费页面
    public function record(){
        if ($this->request->isPost()) {
            // 关键字
            $keywords = $this->request->param('keywords', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $where = ['busid'=>$this->LoginUser['id']];
            if (!empty($keywords)) {
                $where['total'] = ['like', "%$keywords%"];
            }
            $count = $this->RecordModel->where($where)->count();
            // 分页查询 
            $subjectlist = $this->RecordModel->where($where)->page($page, $limit)->select();
            if ($subjectlist) {
                $this->success('', '', ['list' => $subjectlist, 'count' => $count]);
            } else {
                $this->error('暂无更多数据');
            }
        }

        return $this->fetch();
    }
    // 充值页面
    public function pay(){
        return $this->fetch();
    }
}
